package msg

import (
	"context"

	"paper-pro/app/chat/api/internal/svc"
	"paper-pro/app/chat/api/internal/types"
	"paper-pro/pkg/ctxdata"
	"paper-pro/pkg/rpc/chat/client/chatmsgservice"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// list dialog:id chat msgs
func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListLogic) List(req *types.MsgListReq) (resp *types.MsgListResp, err error) {
	userId, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(err, "Chat Msgs Delete: get UserId error: %v", err)
	}

	rpcResp, err := l.svcCtx.ChatMsgRpc.List(l.ctx, &chatmsgservice.ChatMsgListReq{
		DialogId: req.DialogId,
		UserId:   userId,
		Limit:    -1,
	})
	if err != nil {
		return nil, errors.Wrapf(err, "Chat Msgs List: ChatMsgRpc List error: %v", err)
	}

	msgs := make([]types.ChatMsg, len(rpcResp.Msgs))
	for i, msg := range rpcResp.Msgs {
		_ = copier.Copy(&msgs[i], &msg)
	}
	resp = &types.MsgListResp{
		Msgs: msgs,
	}

	return
}
